import { ref, onMounted, onUnmounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDebounceFn, useResizeObserver } from '@vueuse/core'
import { useRoute, useRouter } from 'vue-router'

export const useTableList = (
  searchParams,
  queryList,
  deleteFun,
  customType,
) => {
  // 查询项展开收缩
  const showToggle = ref(false)
  const toggleSearchStatus = ref(false)
  const handleToggleSearch = () => {
    toggleSearchStatus.value = !toggleSearchStatus.value
  }
  const searchFromRef = ref(null)
  const handleResize = (entries) => {
    if (entries && entries.length > 0 && entries[0].contentRect.height > 100) {
      showToggle.value = true
    } else {
      showToggle.value = false
    }
  }

  const tableData = ref([])
  const paginationParams = ref({
    pageIndex: 1,
    pageSize: 10,
  })
  const total = ref(0)
  // 初始化列表
  const loading = ref(false)
  const initTableList = async (pageIndex) => {
    if (pageIndex) {
      paginationParams.value.pageIndex = pageIndex
    }
    const params = { ...searchParams.value, ...paginationParams.value }
    if (queryList) {
      try {
        loading.value = true
        const res = await queryList(params)
        if (['gnss', 'monitor-device'].includes(customType)) {
          total.value = res.count
          tableData.value = res.list
        } else {
          if (res.success) {
            if (customType === 'carPlate') {
              total.value =
                res.data.data?.LPListAuditSearchResult?.LicensePlateInfoList
                  ?.totalMatches || 0
              const tempList =
                res.data.data?.LPListAuditSearchResult?.LicensePlateInfoList
                  ?.LicensePlateInfo
              if (tempList) {
                if (Array.isArray(tempList)) {
                  tableData.value = tempList
                } else {
                  tableData.value = [tempList]
                }
              } else {
                tableData.value = []
              }
            } else if (customType === 'personFace') {
              total.value = res.data.data?.UserInfoSearch?.totalMatches || 0
              tableData.value = res.data.data?.UserInfoSearch?.UserInfo || []
            } else {
              total.value = res.data.count
              tableData.value = res.data.list
            }
          } else {
            ElMessage.error(res.message)
          }
        }
        loading.value = false
      } catch (error) {
        loading.value = false
      }
    }
  }
  // 页数改变
  const handleSizeChange = (val) => {
    paginationParams.value.pageSize = val
    initTableList(1)
  }
  // 重置
  const handleReset = (params, excludes) => {
    if (params) {
      searchParams.value = { ...params }
    } else {
      Object.keys(searchParams.value).forEach((key) => {
        if (excludes && excludes.length) {
          if (!excludes.includes(key)) {
            searchParams.value[key] = ''
          }
        } else {
          searchParams.value[key] = ''
        }
      })
    }

    initTableList(1)
  }
  // 删除
  const handleDelete = (row) => {
    ElMessageBox.confirm('是否确定删除该项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        if (deleteFun) {
          const params = { pkid: row.pkid }
          const res = await deleteFun(params)
          if (res.success) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            initTableList(1)
          } else {
            ElMessage.error(res.message)
          }
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
  }

  /**
   * 根据name获取定义的route对象
   *
   * @param {string} name route定义的name
   */
  const findRouteByName = (name) => {
    return router.getRoutes().find((route) => route.name === name)
  }

  const addRef = ref({})
  const detailRef = ref(null)
  const currentDetail = ref({})
  const router = useRouter()
  const route = useRoute()
  const handleAdd = (title, row, isRoute = false) => {
    if (isRoute) {
      findRouteByName(title).meta.title = '新增'
      router.push({ name: title, query: { ...row } })
    } else {
      currentDetail.value = { ...row }
      addRef.value.title = title
      addRef.value.type = 'add'
      addRef.value.dialogVisible = true
    }
  }
  const handleEdit = (row, title, isRoute = false) => {
    if (isRoute) {
      findRouteByName(title).meta.title = '编辑'
      router.push({ name: title, query: { ...row } })
    } else {
      addRef.value.title = title
      currentDetail.value = { ...row }
      addRef.value.type = 'edit'
      addRef.value.dialogVisible = true
    }
  }
  const handleDetail = (row, title, isRoute = false) => {
    if (isRoute) {
      router.push({ name: title, query: { ...row } })
    } else {
      if (title) {
        detailRef.value.title = title
      }
      currentDetail.value = { ...row }
      detailRef.value.dialogVisible = true
    }
  }
  const handleClose = (isload = false) => {
    currentDetail.value = {}
    if (isload) {
      initTableList(1)
    }
  }
  onMounted(() => {
    useResizeObserver(
      searchFromRef.value,
      useDebounceFn((entries) => {
        handleResize(entries)
      }, 200),
    )
  })
  onUnmounted(() => {})

  return {
    Search,
    showToggle,
    toggleSearchStatus,
    handleToggleSearch,
    searchFromRef,
    tableData,
    paginationParams,
    total,
    loading,
    initTableList,
    handleSizeChange,
    handleReset,
    handleDelete,
    addRef,
    detailRef,
    currentDetail,
    handleAdd,
    handleEdit,
    handleDetail,
    handleClose,
  }
}
